var DBFactory = require('../db/mysql_db');
var indexDao = module.exports;
var CONFIG = require('../config');
var courseDao = require('./course');
var WXBizDataCrypt = require('../util/WXBizDataCrypt');

//机构信息
function getMechanismData(data, cb) {
    var sql = 'select id, mechanism_name, mechanism_avatar, telephone, address, services, crowds, des, ' +
        ' ext_info from mechanism where status = 1 and id = ? ';
    DBFactory.executeSql(sql, [data.mid], 'getMechanismData', function(err, result) {
        if(err) return cb('获取机构信息失败，请重试！');
        if(result.length == 0) return cb('服务器错误，请重试！');
        var mechanismData = result[0];
        var sql = 'select max(cs.price) as max_price, min(cs.price) as min_price from cost_spec as cs ' +
            ' left join course_items ci on cs.sub_course_id = ci.id where ci.mechanism_id = ? ';
        DBFactory.executeSql(sql, [data.mid], 'priceRange', function(err, range) {
            if(err) return cb('获取价格区间错误！');
            mechanismData.maxPrice = range[0].max_price;
            mechanismData.minPrice = range[0].min_price;
            cb(null, mechanismData);
        })
    })
}
//附近商家
indexDao.getNearbyMechanism = function(data, cb) {
    if(!data.size) data.size = 10;
    var sql = 'select mp.id, mp.course_id, m.mechanism_name, m.mechanism_avatar, m.services, m.crowds, m.des, m.id as mid, ' +
        ' round(degrees(acos(sin(radians(?))*sin(radians(mp.`lat`))+cos(radians(?))*cos(radians(mp.`lat`))*cos(radians(?-mp.`lon`))))*69.09) ' +
        ' distance, mp.telephone from mechanism_position as mp left join mechanism as m on mp.mechanism_id = m.id ' +
        ' where m.status = 1 order by distance asc limit ? ';
    DBFactory.executeSql(sql, [data.lat, data.lat, data.lon, data.size], 'getNearbyMechanism', function(err, result) {
        if(err) return cb(err);
        cb(null, result);
    })
}
//获取课程规格选项
indexDao.getCourseSpec = function(data, cb) {
    var sql = data.mid ? 'select * from course_items left join course on course_items.course_id = course.id ' +
        ' where mechanism_id = ? order by course' :
        ' select * from course_items left join course on course_items.course_id = course.id order by course ';
    var arr = data.mid ? [data.mid] : [];
    DBFactory.executeSql(sql, arr, 'getCourseSpec', function(err, result) {
        if(err) return cb('获取课程规格信息失败,请重试！');
        if(result.length == 0) return cb(null, {});
        var course_spec = {};
        result.forEach(function(course) {
            if(!course_spec[course.course]) {
                course_spec[course.course] = [];
                course_spec.spec = course.spec;
            }
            course_spec[course.course].push(course.sub_course);
        })
        cb(null, course_spec);
    })
}

function getValidCourse(data, cb) {
    var arr = [];
    var sql = 'select c.id as c_id, c.course, ci.* from course_items as ci left join course as c on ci.course_id = c.id where c.`status` = 1';
    if(data.mid) {
        sql += ' and ci.mechanism_id = ? ';
        arr.push(data.mid);
    }
    if(data.scid) {
        sql += ' and ci.id = ? ';
        arr.push(data.scid);
    }
    DBFactory.executeSql(sql, arr, 'getValidCourse', function(err, result) {
        if(err) return cb(err);
        if(result.length == 0) return cb('暂无信息,请联系管理员！');
        var courses = {};
        var cid = {};
        result.forEach(function(c) {
            if(parseInt(c.sex) == 0) c.sex = '女';
            if(parseInt(c.sex) == 1) c.sex = '男';
            if(parseInt(c.sex) == 2) c.sex = '不限';
            if(!courses[c.course]) {
                courses[c.course] = {};
                if(!courses[c.course][c.sub_course]) courses[c.course][c.sub_course] = {};
                if(!courses[c.course][c.sub_course][c.crowd]) courses[c.course][c.sub_course][c.crowd] = {};
                if(!courses[c.course][c.sub_course][c.crowd][c.sex]) courses[c.course][c.sub_course][c.crowd][c.sex] = c.id;
            } else {
                if(!courses[c.course][c.sub_course]) courses[c.course][c.sub_course] = {};
                if(!courses[c.course][c.sub_course][c.crowd]) courses[c.course][c.sub_course][c.crowd] = {};
                if(!courses[c.course][c.sub_course][c.crowd][c.sex]) courses[c.course][c.sub_course][c.crowd][c.sex] = c.id;
            }
            if(!cid[c.course]) {
                cid[c.course] = c.c_id;
            }
        })
        var info = {};
        info.courses = courses;
        info.cid = cid;
        if(!data.scid) return cb(null, info);
        getCostSpec(data, function(e, spec) {
            if(e) return cb(e);
            info.spec = spec;
            cb(null, info);
        })
    })
}
function getMValidCourse(data, cb) {
    getMechanismData(data, function(err, mechanism) {
        if(err) return cb(err);
        getValidCourse(data, function(e, c) {
            if(e) return cb(e);
            c.mechanism = mechanism;
            cb(null, c);
        })
    })
}
function getCostSpec(data, cb) {
    var sql = 'select * from cost_spec where sub_course_id = ? ';
    DBFactory.executeSql(sql, [data.scid], 'getValidCourse', function(err, result) {
        if(err) return cb(err);
        if(result.length == 0) return cb('服务器错误！');
        var spec = {};
        result.forEach(function(s) {
            if(!spec[s.lvl]) {
                spec[s.lvl] = {};
                if(!spec[s.lvl][s.target_lvl]) spec[s.lvl][s.target_lvl] = s;
            } else {
                if(!spec[s.lvl][s.target_lvl]) spec[s.lvl][s.target_lvl] = s;
            }
        })
        cb(null, spec);
    })
}
indexDao.getHomeData = function(data, cb) {
    var type = 0;
    if(data.mid) type = 1;
    switch(type) {
        case 0: getValidCourse(data, cb); break;
        case 1: getMValidCourse(data, cb); break;
    }
}

indexDao.evaluate = function(data, cb) {
    var sql = data.mid ? 'select * from course_items left join cost_spec on course_items.id = cost_spec.sub_course_id ' +
        ' where course_items.mechanism_id = ? ' :
        ' select * from course_items left join cost_spec on course_items.id = cost_spec.sub_course_id where 1 ';
    var arr = data.mid ? [data.mid] : [];
    if(data.crowd) {
        sql += ' and crowd = ? ';
        arr.push(data.crowd);
    }
    if(data.sex) {
        sql += ' and sex = ? ';
        arr.push(data.sex);
    }
    if(data.lvl) {
        sql += ' and lvl = ? ';
        arr.push(data.lvl);
    }
    if(data.target_lvl) {
        sql += ' and target_lvl = ? ';
        arr.push(data.target_lvl);
    }
    DBFactory.executeSql(sql, arr, 'evaluate', function(err, result) {
        if(err) return cb(err);
        // 整理数据   不符合条件的    重新筛选 或者 用自己定义的一个方法返回数据
    })
}

//访问记录
indexDao.visit = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var formatData = {};
    ['openid','avatar','url','mechanism_id','course_id','sub_course_id','nick'].forEach(function(key) {
        if(data[key]) formatData[key] = data[key];
    })
    if(formatData['openid']) {
        var sql = 'insert into visitor set ? ';
        DBFactory.executeSql(sql, formatData, 'visit', function(err, result) {
            if(err) return cb(err);
            cb(null, result);
        })
    } else {
        cb(null, null);
    }
}

//用code拿用户信息
function wxGetUserInfo(data) {
    var pc = new WXBizDataCrypt(CONFIG.WX_AUTH.AppID, data.sessionKey);
    var userInfo = pc.decryptData(data.encryptedData , data.iv);
    return userInfo;
}
indexDao.getInfoByCode = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var opt = {};
    opt.url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' +
        CONFIG.WX_AUTH.AppID + '&secret=' + CONFIG.WX_AUTH.AppSecret + '&js_code='+ data.code +'&grant_type=authorization_code';
    opt.method = 'GET';
    customRequest(opt, function(err, body) {
        if(err) return cb('获取openid失败！');
        cb(null, body);

        //2.获取unionid
        // if(body.unionid) return cb(null, body);
        // if((!data.encryptedData || !data.iv || !body.session_key) && !body.unionid) return cb('获取wx_unionId失败，请重试！');
        // data.sessionKey = body.session_key;
        // var userInfo = wxGetUserInfo(data);
        // if(userInfo.unionId) {
        //     body.unionid = userInfo.unionId;
        //     return cb(null, body);
        // } else {
        //     return cb('获取wx_unionId失败！');
        // }
    })
}